<template>
  <el-form ref="formdata" :model="formData" label-width="120px" :rules="rules">
    <base-layout
      :dialog-title="dialogTitle"
      :dialog-visible="dialogVisible"
      visibleContent2
      @dialog-close="dialogClose"
    >
      <template #searchPanel>
        <el-row>
          <el-col :span="12">调拨单基础信息</el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="调拨单号" prop="code">
              <el-input
                v-model="formData.code"
                readonly="readonly"
                disabled
                placeholder="自动生成"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调出门店" prop="outStoreId">
              <el-select
                clearable
                filterable
                class="w-100"
                v-model="formData.outStoreId"
                placeholder="调拨门店"
              >
                <el-option
                  v-for="item in allStores"
                  :key="item.id"
                  :value="item.id"
                  :label="item.storeName"
                />
              </el-select>
              <!-- <job-shop
                v-model="formData.outStoreId"
                class="w-100"
                placeholder="调出门店"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调出仓库" prop="outStorageId">
              <el-select
                v-model="formData.outStorageId"
                placeholder="调出仓库"
                class="w-100"
                @change="requestStorageSiteList"
              >
                <el-option
                  v-for="item in outStorageList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.storageName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调拨原因" prop="allotReason">
              <el-input
                v-model="formData.allotReason"
                placeholder="请输入调拨原因"
              />
              <!-- <el-select
                v-model="formData.allotReason"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dict['调拨原因']"
                  :key="item.index"
                  :value="item.value"
                  :label="item.text"
                />
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单据日期" prop="receiptsTime">
              <el-date-picker
                v-model="formData.receiptsTime"
                value-format="yyyy-MM-dd hh:mm:ss"
                disabled
                type="datetime"
                class="w-100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调入门店" prop="storeId">
              <job-shop
                disabled
                defaultStoreId
                placeholder="调入门店"
                v-model="formData.storeId"
                class="w-100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调入仓库" prop="inStorageId">
              <el-select
                v-model="formData.inStorageId"
                placeholder="调入仓库"
                class="w-100"
              >
                <el-option
                  v-for="item in inStorageList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.storageName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="调拨备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="6"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel>
        <el-row>
          <el-col :span="12">调拨负责人员</el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="管理人员" prop="userName">
              <user-select
                v-model="formData.userName"
                :store-id="formData.storeId"
                @change="userNameHChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                readonly="readonly"
                v-model="formData.phone"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel2>
        <el-row type="flex" align="middle">
          <el-col :span="12">调拨精品列表</el-col>
          <el-col class="text-right" :span="12">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addProductHandle"
              >添加调拨精品</el-button
            >
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <data-table
          has-action
          :is-show-page="false"
          :value="formData.partsList"
          :table-column-attributes="tableColumns"
          :width="160"
        >
          <template #action="{ row, $index }">
            <i
              class="el-icon-delete"
              title="删除"
              style="margin-left: 15px; cursor: pointer"
              @click="handleDataDelete(row, $index)"
            ></i>
          </template>
          <div class="total-count" slot="allNum">
            精品总金额:<span class="money-value"
              >￥{{ formData.brandAmount }}</span
            >
            精品总数:<span class="count-value">{{ formData.brandCount }}</span>
          </div>
        </data-table>
        <div class="text-right mt-10">
          <span class="total-count">
            出库总金额:<span class="money-value"
              >￥{{ formData.brandAmount }}</span
            >
          </span>
          <el-button
            v-permission="!$route.params.id ? authConfig.add : authConfig.edit"
            type="success"
            @click="submitHandle"
            >{{ formData.id !== '' ? '更新调拨单' : '新增调拨单' }}</el-button
          >
        </div>
      </template>
      <template #dialog>
        <select-product-form
          v-if="showProductTable"
          @select="confirmSelectHandle"
        />
      </template>
    </base-layout>
  </el-form>
</template>

<script>
import baseMixin from '@/mixins/base'
import BaseLayout from '@/views/layout/Base'
import UserSelect from '@/components/CommonForm/UserSelect'
import DataTable from '@/components/DataTable'
import { JobShop } from '@/components/index'
import SelectProductForm from '@/components/CommonForm/SelectProductForm'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import store from '@/store'
import {
  findByStore,
  getAllotCode,
  add,
  update,
  getFindById,
  findByStoreIdAndStorageId,
  getFindPosDetail,
} from '@/api/pre-sale/boutiqueStock/transferManagement'
import { mapGetters } from 'vuex'

export default {
  mixins: [
    baseMixin({
      addData: add,
      updateData: update,
      format(res) {
        return res.map((data) => {
          return data
        })
      },
    }),
  ],
  components: { JobShop, BaseLayout, DataTable, SelectProductForm, UserSelect },
  data() {
    return {
      authConfig: {
        add: 'allot:save',
        edit: 'allot:update',
      },
      formData: {
        id: '',
        code: '', // 调拨单号
        storeId: '', // 调入门店
        inStorageId: '', // 调入仓库
        outStoreId: '', // 调出门店
        outStorageId: '', // 调出仓库
        allotReason: '', // 调拨原因
        remark: '', // 备注
        userName: '', // 管理人员
        phone: '', // 联系电话
        brandAmount: 0, // 精品总金额
        brandCount: 0, // 精品总数量
        receiptsTime: parseTimeToYMDHMS(new Date()), // 单据时间
        partsList: [],
      },
      isFirstEdit1: false,
      isFirstEdit2: false,
      rules: {
        receiptsTime: [
          { required: true, message: '请选择单据日期', trigger: 'change' },
        ],
        // outStoreId: [
        //   { required: true, message: '请选择调出门店', trigger: 'change' }
        // ],
        // storeId: [
        //   { required: true, message: '请选择调入门店', trigger: 'change' },
        // ],
        // outStorageId: [
        //   { required: true, message: '请选择调出仓库', trigger: 'change' },
        // ],
        inStorageId: [
          { required: true, message: '请选择调入仓库', trigger: 'change' },
        ],
        allotReason: [
          { required: true, message: '请选择调拨原因', trigger: 'change' },
        ],
        userName: [
          { required: true, message: '请选择管理人员', trigger: 'change' },
        ],
        phone: [
          { required: true, message: '请输入联系方式', trigger: 'change' },
        ],
      },
      outStorageList: [], // 调出仓库
      inStorageList: [], // 调入仓库
      showProductTable: false,
      storageSiteList: [], // 仓位下拉数据
      tableColumns: [
        { name: '精品编号', value: 'partsCode', type: 'text' },
        { name: '精品名称', value: 'partsName', type: 'text' },
        { name: '一级类别', value: 'partsType', type: 'text' },
        { name: '二级类别', value: 'partsUnit', type: 'text' },
        {
          name: '仓位',
          value: 'outStorageSiteId',
          type: 'select',
          action: this.storageSiteChange,
          options: [],
        },
        { name: '仓位编号', value: 'outStorageSiteCode', type: 'text' },
        {
          name: '出库数量',
          value: 'num',
          maxFiledName: 'maxNum',
          type: 'inputNumber',
          action: this.calcData,
        },
        { name: '仓位剩余', value: 'outStorageSiteRemainNum', type: 'text' },
        { name: '采购成本', value: 'purchasePrice', type: 'text' },
        {
          name: '销售价',
          value: 'storagePrice',
          type: 'text',
        },
        {
          name: '总金额',
          value: 'amount',
          type: 'text',
        },
      ],
    }
  },
  watch: {
    // 调入门店联动
    'formData.storeId': {
      handler(value) {
        if (value) {
          this.getInWareHouse(value)
        } else {
          this.getInWareHouse(store.state.user.entryStore)
        }
      },
    },
    // 调出门店联动
    'formData.outStoreId': {
      handler(value) {
        if (value) {
          this.getOutWareHouse(value)
        } else {
          if (!this.isFirstEdit2) {
            // 清空调出仓库
            this.formData.outStorageId = ''
            // 清空仓位和仓位编号
            this.formData.partsList = this.formData.partsList.map((item) => {
              return { ...item, outStorageSiteCode: '', outStorageSiteId: '' }
            })
            this.tableColumns[4].options = []
            this.storageSiteList = []
          }
        }
      },
    },
  },
  methods: {
    // 获取调入仓库
    getInWareHouse() {
      if (!this.formData.storeId) {
        return
      }
      if (this.isFirstEdit1) {
        this.isFirstEdit1 = false
      } else {
        this.formData.inStorageId = ''
        this.formData.userName = ''
        this.formData.phone = ''
      }
      findByStore(this.formData.storeId).then((res) => {
        const { data = [] } = res
        this.inStorageList = data
      })
    },
    // 获取调出仓库
    getOutWareHouse() {
      if (!this.formData.outStoreId) {
        return
      }
      if (this.isFirstEdit2) {
        this.isFirstEdit2 = false
      } else {
        this.formData.outStorageId = ''
      }

      findByStore(this.formData.outStoreId).then((res) => {
        const { data = [] } = res
        this.outStorageList = data
      })
    },

    // 根据调出仓库联动获取仓位信息
    requestStorageSiteList() {
      const { outStoreId, outStorageId } = this.formData
      if (!outStoreId || !outStorageId) {
        return
      }
      if (!this.isFirstEdit2) {
        // 清空仓位和仓位编号
        this.formData.partsList = this.formData.partsList.map((item) => {
          return { ...item, outStorageSiteCode: '', outStorageSiteId: '' }
        })
      }

      findByStoreIdAndStorageId(outStoreId, outStorageId).then((res) => {
        const { data = [] } = res
        data.forEach((item) => {
          item.value = item.storageSiteName
        })
        this.tableColumns[4].options = data
        this.storageSiteList = data
      })
    },
    // 仓位改变
    storageSiteChange(row) {
      const { outStorageSiteId } = row
      const storageSite = this.storageSiteList.find(
        (item) => item.id == outStorageSiteId
      )
      row.outStorageSiteCode = storageSite.storageSiteCode // 仓位编号
      row.storageSiteName = storageSite.storageSiteName
      row.outStorageSiteRemainNum = storageSite.num // 仓位剩余数
      if (outStorageSiteId) {
        row.maxNum = storageSite.num
      } else {
        row.maxNum = 999999
      }
    },

    // 管理人员人选择
    userNameHChange(item) {
      this.formData.userName = item.userName
      this.formData.phone = item.phone
    },
    // 计算当前数据
    calcData(row) {
      const { num, storagePrice } = row
      row.amount = num * storagePrice
      this.calcCountData()
    },
    // 统计所有数据
    calcCountData() {
      let brandAmount = 0 // 总金额
      let brandCount = 0 // 总数量

      this.formData.partsList.forEach((item) => {
        brandAmount += item.amount || 0
        brandCount += item.num || 0
      })
      this.formData.brandAmount = brandAmount
      this.formData.brandCount = brandCount
      this.$forceUpdate()
    },

    // 添加精品显示弹窗
    addProductHandle() {
      this.showProductTable = true
      this.dialogVisible = true
    },
    dialogClose() {
      this.showProductTable = false
      this.dialogVisible = false
    },
    // 添加精品
    confirmSelectHandle(selection) {
      const tableList = []
      selection.forEach((item) => {
        if (!this.tableDataMap[item.id]) {
          tableList.push({
            partsCode: item.orderNo, // 精品编号
            partsName: item.name, // 精品名称
            partsId: item.id, // 精品id
            partsType: item.appLargeOne, // 一级类别
            partsUnit: item.appLargeTwo, // 二级类别
            outStorageSiteId: '', // 仓位
            outStorageSiteCode: '', // 仓位编号
            storageSiteName: '',
            outStorageSiteRemainNum: 0, // 剩余仓位
            num: 0, // 出库数量
            purchasePrice: item.costPrice, // 采购成本
            storagePrice: item.currentPrice, // 销售价
            amount: 0, // 总金额
            maxNum: 999999,
          })
        }
      })
      this.formData.partsList.push(...tableList)
      this.dialogClose()
    },

    handleDataDelete(row, $index) {
      this.formData.tableData.splice($index, 1)
    },
    // 新增调拨单
    submitHandle() {
      this.$refs['formdata'].validate((valid) => {
        if (valid) {
          this.handleDataUpdate(this.formData)
          this.$router.push({ path: '/boutiqueStock/transferManagement' })
        }
      })
    },

    // 新增获取调拨单号
    async getAllotCode() {
      const { data } = await getAllotCode()
      this.formData.code = data
    },
    // 编辑查询详情
    async detail(id) {
      const { data } = await getFindById(id)
      this.isFirstEdit1 = true
      this.isFirstEdit2 = true
      this.formData = data
      if (this.formData.outStoreId === 0) {
        this.formData.outStoreId = null
      }
      if (this.formData.outStorageId === 0) {
        this.formData.outStorageId = null
      }
      // 获取仓位下拉数据
      this.requestStorageSiteList()
      this.formData.partsList = this.formData.partsList.map((item) => {
        if (item.outStorageSiteId === 0) {
          item.maxNum = 999999
          item.outStorageSiteId = null
        } else {
          item.maxNum = item.outStorageSiteRemainNum
        }
        return item
      })
    },
  },
  computed: {
    tableDataMap() {
      const map = {}
      this.formData.partsList.forEach((item, index) => {
        map[item.partsId] = index
      })
      return map
    },
    ...mapGetters(['allStores']),
  },
  created() {
    this.dict = getDict(['调拨原因'])
    this.getInWareHouse(store.state.user.entryStore)
    this.getOutWareHouse(store.state.user.entryStore)
    const id = this.$route.params.id
    if (id) {
      this.formData.id = id
      this.detail(id)
    } else {
      this.getAllotCode() // 新增获取编号
    }
  },
  mounted() {},
}
</script>

<style></style>
